package com.cn.ZhiKeDianShang.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.MainActivity;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.response.RroandCityBean;
import com.cn.ZhiKeDianShang.model.response.UserInfoBean;
import com.cn.ZhiKeDianShang.presenter.LoginUserPresenter;
import com.cn.ZhiKeDianShang.presenter.view.LoginUserView;
import com.cn.ZhiKeDianShang.util.JsonUitl;
import com.cn.ZhiKeDianShang.util.PrefShare;
import com.cn.ZhiKeDianShang.util.TimeSelect.CustomAdressPicker;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.JsonCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/3.
 * do what to 2017/7/3
 */

public class RegistActivity extends BaseActivity<LoginUserView, LoginUserPresenter> implements LoginUserView {

    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_repassword)
    EditText etRepassword;
    @BindView(R.id.et_nickname)
    EditText etNickname;
    @BindView(R.id.tv_adress)
    TextView tvAdress;
    @BindView(R.id.im_right2)
    ImageView imRight2;
    @BindView(R.id.rl_updatenadress)
    RelativeLayout rlUpdatenadress;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_sendcode)
    TextView tvSendcode;
    @BindView(R.id.et_invitationcode)
    EditText etInvitationcode;
    @BindView(R.id.tv_regist)
    TextView tvRegist;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_rules)
    TextView tvRules;


    private int reckonTime = 60;
    private Handler mReckonHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x1) {
                //倒计时  控件背景颜色
                if (tvSendcode != null) {
                    tvSendcode.setText(reckonTime + " " + "S");
                }
                reckonTime--;
                if (reckonTime < 0) {
                    mReckonHandler.sendEmptyMessage(0x2);
                } else {
                    mReckonHandler.sendEmptyMessageDelayed(0x1, 1000);
                }
            } else if (msg.what == 0x2) {
                // 60秒结束
                if (tvSendcode != null) {
                    tvSendcode.setEnabled(true);
                    tvSendcode.setText("获取验证码");
                }
                //控件 没点击背景颜色
//                tvSendcode.setBackgroundResource(R.drawable.ql_l_g_bg_ripple);
                reckonTime = 60;
            }
        }
    };


    @Override
    protected int getNormalLayoutId() {
        return R.layout.activity_regist_info;
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.activity_regist_info;
    }

    @Override
    protected LoginUserPresenter createPresenter() {
        return new LoginUserPresenter(this, this);
    }

    @Override
    protected void initViewsAndEvents() {
        //不允许左滑返回
        mSwipeBackLayout.setEnableGesture(false);
    }

    @Override
    public void onLogin(UserInfoBean resultBean) {

    }

    @Override
    public void requestFailed(String message) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rl_updatenadress, R.id.tv_sendcode, R.id.tv_regist, R.id.tv_login, R.id.tv_rules})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_updatenadress:
                getPro();
                break;
            case R.id.tv_sendcode:
                if (etPhone.getText().toString().length() == 0) {
                    ToastUtil.showShort("请输入手机号码");
                    return;
                }
                smsSend();

                break;
            case R.id.tv_regist:
                regist();
                break;
            case R.id.tv_login:
                startActivity(new Intent(RegistActivity.this, LoginActivity.class));
                finish();
                break;
            case R.id.tv_rules:
                break;
        }
    }


    /**
     * @param
     */
    private void getPro() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.COMMON_PROVINCE)
                .params(params)
                .build()
                .execute(new JsonCallback() {

                    @Override
                    public void onResponse(String result) {
                        RroandCityBean bean = (RroandCityBean) JsonUitl.stringToObject(result, RroandCityBean.class);
                        AdressPicker(bean.getData());
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    CustomAdressPicker customAdressPicker;
    //弹框选择的地址
    String handleproName = "";
    String handlecityName = "";
    String mproId = "";
    String mcityId = "";

    /**
     * 显示时间
     */
    private void AdressPicker(List<RroandCityBean.DataBean> data) {
        //获取当前时间
        //tvElectricalTime.setText(now.split(" ")[0]);
        customAdressPicker = new CustomAdressPicker(RegistActivity.this, data, new CustomAdressPicker.ResultHandler() {
            @Override
            public void handle(String proName, String proId, String cityName, String cityId) {
                Log.d("yyyyy", "返回的省的名字" + proName + "---" + proId + "----" + cityName + "----" + cityId);
                handleproName = proName;
                handlecityName = cityName;
                mproId = proId;
                mcityId = cityId;
                tvAdress.setText(proName + "-" + cityName);

            }

        }); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customAdressPicker.setIsLoop(); // 设置控件循环滚动 （这个在方法里面设置 相应控件能不能循环滑动）
        customAdressPicker.show();
    }


    /**
     * 获得验证码 接口
     */
    private void smsSend() {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", etPhone.getText().toString());
        params.put("event", "1");
        HttpUtils.post().url(AppConfig.SMS_SEND)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {
                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(RegistActivity.this, result)) {
                            ToastUtil.showShort("发送成功 注意查收");
                            tvSendcode.setEnabled(false);
                            //倒计时  控件背景颜色
//                tvSendcode.setBackgroundResource(R.drawable.bg_verify_sure_grey);
                            // 开始倒计时
                            mReckonHandler.sendEmptyMessage(0x1);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * 获得验证码 接口
     */
    private void regist() {
        Map<String, String> params = new HashMap<>();
        params.put("username", etUsername.getText().toString());
        params.put("password", etPassword.getText().toString());
        params.put("repassword", etRepassword.getText().toString());
        params.put("nickname", etNickname.getText().toString());
        params.put("province", mproId);
        params.put("city", mcityId);
        params.put("mobile", etPhone.getText().toString());
        params.put("code", etCode.getText().toString());
        if (!TextUtils.isEmpty(etInvitationcode.getText().toString())) {
            params.put("invitationcode", etInvitationcode.getText().toString());
        }
        HttpUtils.post().url(AppConfig.USER_REGISTER)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {
                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(RegistActivity.this, result)) {
                            ToastUtil.showShort(result.getResultMsg());
                            LoginRegisterResult data = result.getData();
                            PrefShare.getInstance(RegistActivity.this).saveString("token", data.getUserinfo().getToken());
                            PrefShare.getInstance(RegistActivity.this).saveString("userId", data.getUserinfo().getId() + "");
                            startActivity(new Intent(RegistActivity.this, MainActivity.class));
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mReckonHandler.removeCallbacksAndMessages(null);
    }
}
